package com.t235.gc.auth.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

@Controller
@Slf4j
public class UserController {
    @Value("${gitee.url}")
    private String giteeUrl;
    @Value("${gitee.client_id}")
    private String giteeClientId;
    @Value("${gitee.client_secret}")
    private String giteeClientSecret;
    @Value("${gitee.redirect_uri}")
    private String giteeRedirectUri;
    @Value("${gitee.user_uri}")
    private String giteeUserUri;

    @GetMapping("/users/me")
    @ResponseBody
    public Object me(Principal principal) {
        return principal;
    }



    /**
     * 第一步：申请一个授权码
     * @param response
     * @throws IOException
     */
    @GetMapping("/gitee/code")
    public void code(HttpServletResponse response) throws IOException {
        String uri = giteeUrl + "/oauth/authorize?client_id=" + giteeClientId;
        uri += "&redirect_uri=" + java.net.URLEncoder.encode(giteeRedirectUri, "UTF-8");
        uri += "&response_type=code";
        log.info("uri:{}", uri);
        response.sendRedirect(uri);
    }

    /**
     * 回调方法
     * 第二步，通过授权码获取access_token
     * @param code
     */
    @RequestMapping("/gitee/callback")
    public String callback(String code, Model model) {
        log.info("code：{}", code);
        // 第二步，通过授权码获取access_token
        RestTemplate restTemplate = new RestTemplate();
        Map<String, String> body = new HashMap<>();
        body.put("grant_type", "authorization_code");
        body.put("code", code);
        body.put("client_id", giteeClientId);
        body.put("redirect_uri", giteeRedirectUri);
        body.put("client_secret", giteeClientSecret);
        HttpEntity httpEntity = new HttpEntity(body);
        Map map = restTemplate.postForObject(giteeUrl + "/oauth/token", httpEntity, Map.class);
        log.info("map:{}", map);
        // 第三步，通过access_token获取资源（gitee上的用户信息）
        String access_token = (String) map.get("access_token");
        Map userInfo = restTemplate.getForObject(giteeUserUri + "?access_token=" + access_token, Map.class);
        log.info("userInfo:{}", userInfo);
        // 第四步，将码云账号和本系统的账号绑定
        model.addAttribute("userInfo", userInfo);
        return "binding";
    }
}
